import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

axios.defaults.baseURL = 'http://localhost:19090'

Vue.prototype.axios = axios

Vue.use(ElementUI);

Vue.config.productionTip = false

axios.interceptors.request.use(
    config => {
      const tokenStr = window.localStorage.getItem('cecFrontToken')
      //console.log(tokenStr)
      if (tokenStr) {
        config.headers['Authorization'] = tokenStr
      }
      console.log("请求参数:", config);
      return config
    },error => {
      return Promise.reject(error);
    }
)
router.beforeEach((to, from, next) => {
  const tokenStr = window.localStorage.getItem('cecFrontToken');
  if (to.path == "/web") {
    next();
  } else if (to.path == "/login") {
    next();
  } else if (tokenStr == null) {
    ElementUI.Message({
      message: '请先登录!',
      type: 'error'
    });
    next({path: "/login"});
  } else {
    next();
  }
});

axios.interceptors.response.use(response => {
      console.log('响应回来：',response.data)
      if (response.data.state == 40900) {
        if (window.localStorage.getItem("cecFrontToken") != null) {
          console.log("即将跳转页面")
          router.push("/login");
          window.localStorage.removeItem("cecFrontToken");
          ElementUI.Message({
            message: '身份已失效,请重新登录',
            type: 'error'
          });
        }
      } else if (response.data.state == 40901 || response.data.state == 40902 || response.data.state == 50100) {
        if (window.localStorage.getItem("cecFrontToken") != null) {
          router.push("/login");
          ElementUI.Message({
            message: response.data.message,
            type: 'error'
          });
          window.localStorage.removeItem("cecFrontToken");
          //跳转
        }
      } else {
        return response
      }
    },error => {
      console.log("返回错误:", error);
      return Promise.reject(error);
    }
)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
